/**
 * 搜索并选择历史客户
 */

var clienter;

//页面载入初始化
$( "body" ).ready( function( e )
{
	clienter = new ClientSelector();
	clienter.init();
} );

//窗口大小改变
$( window ).resize( function( e )
{
	if( clienter.visibled() )
	{
		clienter.relocate();
	}
} );

function ClientSelector()
{
	var html = "<div id='__DIV_CLIENT_SELECTOR_MASK' style='display:block;position:absolute;z-index:8999;background-color:#000;filter:alpha(opacity=20);opacity:0.2;'></div>"
			+ "<div id='__DIV_CLIENT_SELECTOR' style='position:absolute;z-index:9000;'>"
			+ "<dt><span id='title'>历史客户资源搜索</span><a id='btn_cancel'>[ 取消 ]</a> <a id='btn_enter'>[ 确定 ]</a></dt>"
			+ "<div id='form'>"
			+ "<label>过滤条件：<span>（多条件精确搜索按顺序以空格分开，若无空格则尝试搜索符合条件的所有记录）</span></label>"
			+ "<input id='condition' type='text' size='80' placeholder='姓名/学员名/渠道/类别/电话/邮箱/QQ/地区'/>"
			+ "</div>"
			+ "<div id='body'><ul></ul></div>" + "</div>";

	var $mask;
	var $box;
	var $body;
	var $list;
	var $ipt;
	var callback;

	var selectedId;
	var tmpData;// 临时查询的数据集合

	var _moveable = false;

	this.selected = function()
	{
		return selectedId;
	};

	this.init = function()
	{
		$( "body" ).append( html );
		$box = $( "#__DIV_CLIENT_SELECTOR" );
		$mask = $( "#__DIV_CLIENT_SELECTOR_MASK" );
		$ipt = $( "#form > #condition" );
		$body = $box.find( "#body" );
		$list = $body.find( "ul" );
		empty_list();

		$ipt.bind( "keyup", keyupHandler );

		$box.find( "dt" ).bind( { mousedown: function( e )
		{
			_moveable = true;

			// 鼠标相对于当前窗口的位置
			var offsetX = e.pageX - $box.x();
			var offsetY = e.pageY - $box.y();

			$( "body" ).bind( "mousemove", { ox: offsetX, oy: offsetY }, function( e )
			{
				if( _moveable )
				{
					$box.move( e.pageX - e.data.ox, e.pageY - e.data.oy );
				}
			} );
		}, mouseup: function( e )
		{
			_moveable = false;
			$( "body" ).unbind( "mousemove" );
		} } );

		$box.find( "#btn_cancel" ).click( { cur: this }, function( e )
		{
			e.stopPropagation();
			var pcur = e.data.cur;
			pcur.close();
		} );
		$box.find( "#btn_enter" ).click( { cur: this }, function( e )
		{
			e.stopPropagation();
			var pcur = e.data.cur;

			if( typeof ( callback ) == "function" && tmpData != null && selectedId != -1 )
			{
				callback( tmpData[ selectedId ] );
			}

			pcur.close();
		} );

		$box.hide();
		$mask.hide();
	};

	var _timeoutid = null;
	var _valChanged = false;

	function keyupHandler( e )
	{
		_valChanged = true;
		_timeoutid && clearTimeout( _timeoutid );
		_timeoutid = setTimeout( postHandler, 300 );
	}

	function postHandler()
	{
		if( !_valChanged )
			return;

		// 还原，等下次利用
		_valChanged = false;
		_timeoutid = null;

		// 搜索条件
		var val = $ipt.val();

		if( val == "" )
		{
			empty_list();
		}
		else
		{
			$.post( "client_search.php", { key: val }, function( value )
			{
				var d = $.parseJSON( value );
				tmpData = d;
				selectedId = -1;

				if( d.err == 0 )
				{
					$list.find( "li" ).unbind( "click" );
					$list.empty();

					var size = parseInt( d[ 'size' ] );
					for( var i = 0; i < size; i++ )
					{
						var v = d[ i ];
						var phone = empty( v.phone ) ? "无" : v.phone;
						var qq = empty( v.qq ) ? "无" : v.qq;
						var address = "";

						if( !empty( v.province ) )
						{
							address += v.province;
							if( !empty( v.city ) )
								address += " - " + v.city;
						}

						if( !empty( v.address ) )
							address += " - " + v.address;

						empty( address ) && ( address = "未知" );

						$list.append( "<li rel='"
								+ i
								+ "'><span class='stress'>"
								+ v.nickname
								+ "</span>（"
								+ address
								+ "）"
								+ ( v.invalid == 1 ? "<em class='caption'> - 无效客户</em>"
										: "<em class='valid'> - 有效客户</em>" )
								+ "<p class='__CLIENT_INFO_LIST'><span><b>渠道</b>：" + v.sourcens
								+ "</span><span><b>类别</b>：" + v.categoryns + "</span><span><b>电话</b>："
								+ phone + "</span></p></li>" );
					}
					$list.find( "li" ).bind( { click: itemClickHandler, dblclick: itemClickHandler } );

					$list.find( "li" ).each( function()
					{
						disableSelect( this );
					} );

				}
				else
				{
					infopad.err( d.msg );
				}
			} );
		}
	}

	function itemClickHandler( e )
	{
		var lastId = parseInt( $list.find( "li.selected" ).attr( "rel" ) );
		var curId = parseInt( $( this ).attr( "rel" ) );
		$list.find( "li" ).removeClass( "selected" );

		if( lastId != curId )
		{
			selectedId = curId;
			$( this ).addClass( "selected" );
		}
		else
		{
			selectedId = -1;
		}

		if( e.type == "dblclick" )
		{
			if( typeof ( callback ) == "function" )
			{
				callback( tmpData[ selectedId ] );
			}
			clienter.close();
		}
	}

	function empty_list()
	{
		$list.empty();
		$list
				.append( "<li class='empty'>请输入搜索条件，自动匹配的结果在此处列出。<br><br><p class='bold'>条件格式：</p>"
						+ "<p>（1）<span class='bold'>单条件</span> \"姓名/学员名/渠道/类别/电话/邮箱/QQ\" 任一包含条件的记录。</p>"
						+ "<p>（2）<span class='bold'>顺序多条件</span> 如\"张三 学员 商桥 学员客户 15387346628 xxx@126.com 29134\"，至少须两个条件，以空格分开。</p>"
						+ "<p style='word-break:break-all;'>（3）<span class='bold'>无序精确条件</span> 如\"姓名=张三\"、\"学员=张某某\"、\"渠道=商桥\"、\"类别=广告推销\"、\"电话=15387346628\"、\"邮箱=xxx@126.com\"、\"QQ=29134\"。</p>"
						+ "<p><br><span class='bold'>提醒：</span> 条件内容都是模糊查询，可不用写全。精确条件项目可不按顺序设置。</p>"
						+ "</li>" );
	};

	// 是否显示
	this.visibled = function()
	{
		return $box.visible();
	};

	// 显示单条信息
	this.open = function()
	{
		this.relocate();
		$box.fadeIn( 150 );
		$mask.fadeIn( 150 );
	};

	this.reset = function()
	{
		selectedId = -1;
		tmpData = null;
		$ipt.val( "" );
		empty_list();
	};

	this.relocate = function()
	{
		var bw = $( "body" ).width();
		var bh = $( "body" ).height();
		var w = $box.width();
		var h = $box.height();

		$mask.width( bw + 5 );
		$mask.height( bh );
		$mask.move( 0, 0 );
		$box.move( ( bw - w ) / 2, ( bh - h ) / 2 * 0.8 );
	};

	this.close = function()
	{
		$box.fadeOut( 150 );
		$mask.fadeOut( 150 );
	};

	this.setCallback = function( fn )
	{
		callback = fn;
	};
}
